//
//  CCTestViewController.m
//  Party
//
//  Created by its on 15/3/9.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCPartyViewController.h"

#import "CCPartyCellModel.h"
#import "CETableViewBindingHelper.h"
#import "CCPartyCell.h"
#import "MJRefresh.h"
#import "CCPartyCellViewModel.h"
#import "CCDetailViewController.h"
#import "CCDetailModel.h"
#import "CCDetailViewModel.h"

@interface CCPartyViewController ()
@property (strong, nonatomic) CCPartyViewModel *viewModel;
@property (strong, nonatomic) NSMutableDictionary *offscreenCells;
@end

@implementation CCPartyViewController

- (instancetype)initWithViewModel:(CCPartyViewModel *)viewModel {
  if (self = [super init]) {
    _viewModel = viewModel;
    _offscreenCells = [NSMutableDictionary dictionary];
  }
  return self;
}

- (void)loadView {
  UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  view.backgroundColor = [UIColor whiteColor];
  self.view = view;
}
- (void)viewDidLoad {
  [self setupBar];
  [self setupUI];
  [self setupRefresh];
  [self viewWithCSS];
  [self bindWithViewModel];
  [self setViewModelActive];
  [super viewDidLoad];
}

- (void) viewDidDisappear:(BOOL)animated {
  [self setViewModelInactive];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
}

- (void) setupBar {
  RAC(self, title) = RACObserve(self.viewModel, viewTitleString);
}

- (void)setupUI {
  VIEW(
       self.tableView = [[UITableView alloc] initWithFrame:CGRectZero
                                                         style:UITableViewStylePlain];
       self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       self.tableView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:243/255.0f alpha:1];
       [self.view addSubview:self.tableView];
       self.tableView.delegate = self;
       self.tableView.dataSource = self;
  )
}

- (void) viewWithCSS {
//  CSS
  [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self.view);
  }];
  
}

- (void) bindWithViewModel {
  [[self.viewModel upPull] subscribeNext:^(id x) {
    if (x == nil) {
      // show hub
      [CCProgressHUD showHUBInView:self.view withTimeOut:0 str:@"请稍后"];
    }
  } error:^(NSError *error) {
    // show error hub
    [CCProgressHUD showHUBInView:self.view withTimeOut:2 str:@"出错啦"];
  } completed:^{
    [self.tableView reloadData];
    // hidden hub
    [CCProgressHUD hiddenHUBFromView:self.view];
  }];
}

- (void) setViewModelActive {
  self.viewModel.active = YES;
}

- (void) setViewModelInactive {
  self.viewModel.active = NO;
}

- (void)setupRefresh
{
  @weakify(self);
  [self.tableView addHeaderWithCallback:^{
    @strongify(self);
    [[self.viewModel upPull] subscribeNext:^(id x) {
      if (x == nil) {
        // show hub
        [CCProgressHUD showHUBInView:self.view withTimeOut:0 str:@"请稍后"];
      }
    } error:^(NSError *error) {
      // show error hub
      [CCProgressHUD showHUBInView:self.view withTimeOut:2 str:@"出错啦"];
    } completed:^{
      [self.tableView headerEndRefreshing];
      [self.tableView reloadData];
      [CCProgressHUD hiddenHUBFromView:self.view];
    }];
  }];
  
  [self.tableView addFooterWithCallback:^{
    @strongify(self);
    [[self.viewModel downPull] subscribeNext:^(id x) {
      if (x == nil) {
        // show hub
        [CCProgressHUD showHUBInView:self.view withTimeOut:0 str:@"请稍后"];
      }
    } error:^(NSError *error) {
      [CCProgressHUD showHUBInView:self.view withTimeOut:2 str:@"出错啦"];
    } completed:^{
      [self.tableView footerEndRefreshing];
      [self.tableView reloadData];
    }];
  }];
}


#pragma mark uitableview datasource
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  CCPartyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
  if (cell == nil) {
    cell = [[CCPartyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
  }
  CCPartyCellModel *cellmodel = [[CCPartyCellModel alloc] initWithData: self.viewModel.resultArray[indexPath.row]];
  CCPartyCellViewModel *cellViewModel = [[CCPartyCellViewModel alloc] initWithModel:cellmodel];
  [cell bindViewModel: cellViewModel];
  return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.viewModel.resultArray.count;
}

#pragma mark uitableview delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSString *reuseIdentifier = @"cell";
  // Use the dictionary of offscreen cells to get a cell for the reuse identifier, creating a cell and storing
  // it in the dictionary if one hasn't already been added for the reuse identifier.
  // WARNING: Don't call the table view's dequeueReusableCellWithIdentifier: method here because this will result
  // in a memory leak as the cell is created but never returned from the tableView:cellForRowAtIndexPath: method!
  CCPartyCell *cell = [self.offscreenCells objectForKey:reuseIdentifier];
  if (!cell) {
    cell = [[CCPartyCell alloc] init];
    [self.offscreenCells setObject:cell forKey:reuseIdentifier];
  }
  CCPartyCellModel *cellmodel = [[CCPartyCellModel alloc] initWithData: self.viewModel.resultArray[indexPath.row]];
  CCPartyCellViewModel *cellViewModel = [[CCPartyCellViewModel alloc] initWithModel:cellmodel];
  [cell bindViewModel: cellViewModel];
  CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
  return height;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  CCPartyResult *result =  self.viewModel.resultArray[indexPath.row];
  CCDetailModel *model = [[CCDetailModel alloc] initWitActivityID: result.activityID];
  CCDetailViewModel *viewModel = [[CCDetailViewModel alloc] initWithModel: model];
  CCDetailViewController *viewController = [[CCDetailViewController alloc] initWithViewModel: viewModel];
  [self.navigationController pushViewController:viewController animated:YES];
}
@end














